package org.openit.portail.service.impl;

import java.util.Date;
import java.util.List;

import org.openit.portail.dao.ClientDao;
import org.openit.portail.dao.UserSystemDao;
import org.openit.portail.model.UserSystem;
import org.openit.portail.service.UserSystemService;
import org.openit.portail.service.UtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service(value="userSystemService")
public class UserSystemServiceImpl implements UserSystemService,UserDetailsService {
	
	@Autowired(required=true)
	private UserSystemDao userSystemDao;
	@Autowired(required=true)
	private ClientDao clientDao;
	@Autowired
	private UtilService utilService;
	@Transactional(readOnly=true)
	public UserSystem get(Long id) {
		return userSystemDao.get(id);
	}

	@Transactional
	public void delete(UserSystem user) {
		userSystemDao.delete(user);
	}

	@Transactional(readOnly=true)
	public List<UserSystem> findAll() {
		return userSystemDao.findAll();
	}

	@Transactional
	public void save(UserSystem user) throws Exception {
		if(clientDao.getByEmail(user.getEmail())!=null){
			throw new Exception();
		}
		user.setIdModificationUser(utilService.getConnectedUserSystem());
		user.setDtModification(new Date());
		userSystemDao.save(user);
	}

	@Transactional
	public void saveAll(List<UserSystem> users) {
		for (UserSystem user : users)
			userSystemDao.save(user);
	}
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		UserDetails userDetails;
		userDetails=userSystemDao.getByEmail(username);
		if(userDetails!=null)
		return userDetails;
		else
		{
			userDetails=clientDao.getByEmail(username);
			if(userDetails!=null)
				return userDetails;
			return null;
		}
		

	}
	
}
